package com.lightheart.sphr.xiaobinggan.module.home.ui;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Toast;

import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.guwu.common.largeimage.LargeImageView;
import com.guwu.common.largeimage.factory.FileBitmapDecoderFactory;
import com.lightheart.sphr.xiaobinggan.R;
import com.lightheart.sphr.xiaobinggan.base.BaseFragment;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;

import butterknife.BindView;

/**
 * 大图展示
 */
public class BigImageFragment extends BaseFragment {
    @BindView(R.id.photo_view)
    LargeImageView photoView;
    private LocalMedia media;
    private int position;

    public static BigImageFragment getInstance(int position, LocalMedia media){
        BigImageFragment fragment = new BigImageFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("position", position);
        bundle.putParcelable("data", media);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_big_image;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initView(View view) {
        position = getArguments().getInt("position", -1);
        media = getArguments().getParcelable("data");

//        Glide.with(getActivity()).asBitmap().load(media.getPath()).into(photoView);
        //缩放大小
        photoView.setCriticalScaleValueHook(new LargeImageView.CriticalScaleValueHook() {
            @Override
            public float getMinScale(LargeImageView largeImageView, int imageWidth, int imageHeight, float suggestMinScale) {
                return 1;
            }

            @Override
            public float getMaxScale(LargeImageView largeImageView, int imageWidth, int imageHeight, float suggestMaxScale) {
                return 2;
            }
        });

        photoView.setOnClickListener( v -> ToastUtils.showShort( "点点就好" ) );

        //下载图片
        Glide.with(getActivity()).downloadOnly().load(media.getPath()).into( new SimpleTarget<File>() {
            @Override
            public void onResourceReady(@NonNull File resource, @Nullable Transition<? super File> transition) {
                if (resource != null) {
                    try {
                        //获取到下载得到的图片，进行本地保存
                        photoView.setImage(new FileBitmapDecoderFactory(resource));
                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(getActivity(), "加载失败", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }
}
